import axios from "axios"
import { ElMessage } from "element-plus"
import { useRouter } from "vue-router"

export const API_TOKEN_STORAGE_KEY = 'storaged_tp6_api_token'

export default async function (config) {
  // config.baseURL = process.env.VUE_APP_API_BASE_URL
  config.baseURL = import.meta.env.VITE_APP_API_BASE_URL
  config.headers = {
    'Accept': 'application/json'
  }
  const token = localStorage.getItem(API_TOKEN_STORAGE_KEY)
  if (token) {
    config.headers['Authorization'] = token
  }

  try {
    const resp = await axios(config)
    // console.log(resp)
    if (resp.data) {
      if (resp.data.code == 1) {
        return resp.data.data
      } else {
        if (resp.data.code == 10001 || resp.data.code == 10002) {
          // router.replace('/login')
          localStorage.removeItem(API_TOKEN_STORAGE_KEY)
          window.location.href = window.location.pathname
        }
        throw resp.data
      }
    } else {
      throw resp
    }
  } catch (err) {
    console.log('err', err, err.response)
    if (err.response && err.response.data) {
      ElMessage.error(err.response.data.msg ? err.response.data.msg : '出现了错误')
      throw err.response.data
    }
    ElMessage.error(err.msg ? err.msg : (err.message ? err.message : '出现了错误'))
    throw err
  }
}

export const imgUploadApi = import.meta.env.VITE_APP_API_BASE_URL + 'admin/image/upload'

export function getImgUrl(url) {
  return import.meta.env.VITE_APP_IMG_BASE_URL + url
}